package com.softgroup.breath.easyecgproject.myapi;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Shader;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.softgroup.breath.easyecgproject.R;
import com.softgroup.breath.easyecgproject.entry.UserSendInfo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.softgroup.breath.easyecgproject.utils.IOStreamUtil.readTextFromSDcard;

/**
 * Created by Administrator on 2017/11/23.
 */

public class MyOkHttpTask extends AsyncTask<String, Integer, String> {

    private OkHttpClient mOkHttpClient;
    private Request request;
    private Call call;
    private boolean isNormal;
    private final String URL_HOST = "http://182.92.106.31/datatest/";
    private final String END_STRING = ".dat";
    private final String URL_ECG = "http://182.92.106.31/junke/pad/ecgdata";
    private final String URL_ORG = "http://182.92.106.31/datatest/orgdata/";
    private final String URL_EASY_USER = "http://182.92.106.31/yiecg_api.php";
    private final String URL_EASY_IMAGE = "http://182.92.106.31/yiecg_pic_upload.php";
    private final String INFO_MODE = "0";
    private final String FILE_MODE = "1";
    private String url;
    private String defaultResult = "请求失败";
    private String cacheFinish = "缓存完成";
    private String exception = "请求异常";
    private String getMsg = "默认数据";
    private byte[] bytes;
    private ProgressDialog dialog;
    private Context context;
    private String testUrl = "00_85741bb50d4f4ac7a1_7F:B2:92:BF:9D:4C0000000_20180712165941.dat";
    private String string;
    private UserSendInfo userSendInfo;
    private Gson gson;

    public MyOkHttpTask(Context context) {
        this.context = context;
        gson = new Gson();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mOkHttpClient = new OkHttpClient();
        userSendInfo = UserSendInfo.getInstance();
        dialog = new ProgressDialog(context);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setTitle("加载中，请稍后...");
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
    }

    @Override
    protected String doInBackground(final String... params) {
        publishProgress(new Integer[]{1});
//        url = URL_HOST;
//        for (String s : params) {
//            url += s;
//        }
        Log.e("cacae_finish", URL_ORG + testUrl);
        RequestBody body = null;
        switch (params[0]) {
            case INFO_MODE:
                userSendInfo.setUsername(params[1]);
                userSendInfo.setUsersex(params[2]);
                userSendInfo.setUserage(params[3]);
                body = RequestBody.create(null, gson.toJson(userSendInfo));
                request = new Request.Builder().url(URL_EASY_USER).post(body).build();
                break;
            case FILE_MODE:
                File file = new File(params[1]);
                Log.e("okhttp_715", file.getName() + "" + file.length());
                if (file.length() == 0) {
                    return "";
                }
                body = RequestBody.create(MediaType.parse("image/png"), file);
                MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
                requestBody.addFormDataPart("file", file.getName(), body).addFormDataPart("uid", UUID.randomUUID().toString());
//                MultipartBody.Builder builder = new MultipartBody.Builder()
//                        .setType(MultipartBody.FORM)
//                        .addFormDataPart("image", file.getName(),
//                                RequestBody.create(MediaType.parse("png"), file));
                body = requestBody.build();
                request = new Request.Builder().url(URL_EASY_IMAGE).post(body).build();
                break;
            default:
                break;
        }
//        request = new Request.Builder().url(testUrl).build();
        call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhtttp_715", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    string = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                getMsg = cacheFinish;
            }
        });
//        request = new Request.Builder().url(URL_ECG + params[0] + ".dat.json").build();
//        Log.e("cacae_finish", URL_ECG + params[0] + ".dat.json");
////        request = new Request.Builder().url(testUrl).build();
//        call = mOkHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                getMsg = response.body().string();
//                Log.e("okhtttp_715", "string");
//            }
//        });
//        int b = 0;
//        while (b < 20 & bytes == null) {
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            b++;
//        }

        while (getMsg.equals("默认数据")) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return string;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        dialog.dismiss();
        Log.e("okhttp", s);
//        if (s.equals(defaultResult) | s.equals(exception)) {
//            if (okHttpTaskCallBack != null) {
//                okHttpTaskCallBack.onMsg(s);
//            }
//        } else if (s.equals(cacheFinish)) {
        if (okHttpTaskCallBack != null) {
            okHttpTaskCallBack.onBytes(bytes);
            okHttpTaskCallBack.onPostTask();
        }
//        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        dialog.show();
        super.onProgressUpdate(values);
    }

    private OkHttpTaskCallBack okHttpTaskCallBack;

    public void setOkHttpTaskCallBack(OkHttpTaskCallBack okHttpTaskCallBack) {
        this.okHttpTaskCallBack = okHttpTaskCallBack;
    }

    public interface OkHttpTaskCallBack {
        void onPostTask();

        void onBytes(byte[] bytes);

        void onMsg(String msg);
    }

}
